<template>
	<div class="md-tree-selector">
		<v-text-field readonly @click.native="onOpen" v-model="selectMenu" v-bind="{...$attrs, ...$props}"/>
		<tree-select v-model="data" :options="options" ref="tree" @select="onSelect"/>
	</div>
</template>

<script>
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import MdMVVMObject from '@/common/mixins/MdMVVMObject';
import MenuApi from '@/common/api/MenuApi';

export default {
	name: 'MdTreeSelector',
	components: {TreeSelect},
	mixins: [MdMVVMObject],
	data() {
		return {
			options: [],
			selectMenu: undefined
		}
	},
	created() {
		this.getMenuList();
	},
	methods: {
		getMenuList() {
			MenuApi.list({menuType: 'menu,list'}).then(res => {
				this.$utils.responseHandler(res).then(({data}) => {
					if (!data) {
						this.options = [{id: 'root', label: '根菜单'}]
					} else {
						this.options = [
							{id: 'root', label: '根菜单'},
							...this.buildTree(data)
						]
					}
				})
			})
		},
		buildTree(list = []) {
			return list.map(item => {
				if (item.id === this.data) {
					this.selectMenu = item.menuName
				}
				let data = {
					id: item.id,
					label: item.menuName
				}
				if (item.children) {
					data.children = this.buildTree(item.children);
				}
				return data;
			})
		},
		onOpen() {
			if (this.$refs.tree.menu.isOpen) {
				this.$refs.tree.closeMenu();
			} else {
				this.$refs.tree.openMenu();
			}
		},
		onSelect({id, label}) {
			this.selectMenu = label;
			console.info(label)
		},
		watchValue() {
			this.selectMenu = this.data === 'root' ? '根菜单'  : '';
			this.getMenuList();
		}
	}

}
</script>

<style scoped lang="scss">
.md-tree-selector {
	position: relative;

	.vue-treeselect {
		position: absolute;
		left: 0;
		bottom: 20px;
		right: 0;

		::v-deep {
			.vue-treeselect__control {
				display: none;
				margin-top: -44px;
			}

			.vue-treeselect__control,
			.vue-treeselect__single-value,
			.vue-treeselect__menu {
				.vue-treeselect__option {
					line-height: 40px;
				}
			}
		}
	}
}
</style>